package com.springcloud.alibaba.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        log.info("block exception handler ---------" + e.getRule());

        Map r = new HashMap();
        if(e instanceof FlowException) {
            r.put("code", 100);
            r.put("msg", "接口限流");
        }else if(e instanceof DegradeException) {
            r.put("code", 101);
            r.put("msg", "服务降级");
        }else if(e instanceof ParamFlowException) {
            r.put("code", 102);
            r.put("msg", "热点参数降级");
        }else if(e instanceof SystemBlockException) {
            r.put("code", 103);
            r.put("msg", "触发系统的保护规则");
        }else if(e instanceof AuthorityException) {
            r.put("code", 104);
            r.put("msg", "授权规则不通过");
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), r);
    }

}
